package com.bob.common.utils;

import com.bob.common.DataStore;
import com.bob.common.bean.CommitInfo;
import com.bob.common.bean.Constant;
import com.bob.common.bean.DiffItem;
import com.bob.common.bean.ResourcesRef;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtil extends cn.hutool.core.io.FileUtil {
    static Log logger = new SystemStreamLog();

    /**
     * 复制java文件到补丁目录 针对打包为war的web项目
     * @param s java源文件  "F:\\dev\\cczyz\\cczyz\\cczyz_web\\src\\main\\java\\com\\hq\\controller\\register\\RegisterViewController.java"
     * @param p 补丁目录
     */
    public static void copyJavaFileToPatchDir(final String s, final ResourcesRef resourcesRef, final File baseDir, final File outputDirectory, final String finalName, final File p) {
        String s3 = s;
        if(!p.exists()){
            FileUtil.mkdir(p);
        }
        //替换后缀名 , 替换路径得到打包后的文件
        String classTarget = (s3.substring(0, s.lastIndexOf(Constant.FILETYPE_JAVA)) + Constant.FILETYPE_CLASS)
                .replace(baseDir.getAbsolutePath(),outputDirectory.getAbsolutePath() +File.separator+finalName)
                .replace(resourcesRef.getS(), resourcesRef.getP());
        // /home/bob/文档/workspace/cczyz/cczyz_weixin/target/cczyz_weixin-0.0.1-SNAPSHOT/WEB-INF/classes/com/hq/controller/login/LoginWxViewController.class
        File file = new File(classTarget);
        if(file.exists()){

            // /home/bob/文档/patch/2021-08-14-05-42-47/cczyz_weixin-0.0.1-SNAPSHOT//WEB-INF/classes/com/hq/controller/login
            String pp = file.getParentFile().getAbsolutePath().replace(finalName,"").replace(outputDirectory.getAbsolutePath(),p.getAbsolutePath());
            FileUtil.mkdir(pp);
            FileUtil.copy(new File(classTarget),new File(pp),true);
            logger.info(String.format("=== 复制文件到补丁目录成功 ： "));
            logger.info(String.format("=== \t\t\t\t  %s \t===>>\t %s ", classTarget,pp));

            // 处理含有内部类的情况
            String fileName = FileUtil.getPrefix(file);
            for (File l : FileUtil.ls(file.getParentFile().getAbsolutePath())) {
                String lName = FileUtil.getPrefix(l);
                if (lName.startsWith(fileName+"$") && FileUtil.getType(file).equals(FileUtil.getType(l)) ){
                    FileUtil.copy(l,new File(pp),true);
                    logger.info(String.format("=== 复制文件到补丁目录成功 ： "));
                    logger.info(String.format("=== \t\t\t\t  %s \t===>>\t %s ", l,pp));
                }
            }
        }else {
            logger.error(String.format("=== 复制文件到补丁目录失败 ：%s \t===>>\t %s ,源文件为 %s ", classTarget,p.getAbsolutePath(),s));
        }
    }

    /**
     * 写入变更日志到补丁文件
     *
     * @return
     */
    public static void writeChangeLogToPatchFile(File patchOutPath) {
        List<DiffItem> diffItemList = DataStore.getDataStore().getDiffItems()
                .stream().sorted(Comparator.nullsLast(Comparator.comparing(DiffItem::getGroupName)).thenComparing(DiffItem::getPath))
                .collect(Collectors.toList());
        Iterator<DiffItem> diffItems = diffItemList.iterator();

        String configPatchPath = patchOutPath.getAbsolutePath();
        String path = configPatchPath+File.separator+Constant.FILE_NAME_0 + ".txt";

        File desFilePath = new File(configPatchPath);
        if (!desFilePath.exists()) {
            desFilePath.mkdirs();
        }

        File file = new File(path);
           // file.deleteOnExit();
        FileWriter fw = null;
        BufferedWriter writer = null;

        try {
            fw = new FileWriter(file);
            writer = new BufferedWriter(fw);

            while (diffItems.hasNext()) {
                DiffItem diffItem = diffItems.next();
                writer.write(diffItem.getGroupName() + "：\t" + diffItem.getPath());
                writer.newLine();
            }

            writer.newLine();
            for (CommitInfo commitInfo : DataStore.getDataStore().getCommitInfos()) {
                writer.write(commitInfo.getMessage());
                writer.newLine();
            }
            writer.flush();
        } catch (Exception var18) {
            logger.error("=== 写入变更日志到补丁文件失败！", var18);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void openFolder(@NotNull File file){
        if (file == null || !file.exists()){
            return;
        }
        if ((Boolean) DataStore.getDataStore().getData().getOrDefault(Constant.CACHE_KEY_openFolder,false)){
            return;
        }

        logger.info(String.format("=== 正在打开文件夹  %s ", file));
        String os = ShellUtil.getOs();
        switch (os){
            case Constant.SYSTEM_WINDOWS:
                ShellUtil.cmdExec("start "+file.getAbsolutePath());
                break;
            case Constant.SYSTEM_LINUX:
                String [] cmd2 ={ "/usr/bin/nautilus","-s",file.getAbsolutePath()+" &"};
                ShellUtil.cmdExec(cmd2);
                break;
            default:
                return;
        }
        DataStore.getDataStore().getData().putIfAbsent(Constant.CACHE_KEY_openFolder,true);
    }
}
